#include <string.h>
#include <stdio.h>
#include "database.h"
#include "stack.h"

int mkdir_command(MYSQL* conn, DirStack* stack, const char* name, const char* user_name) {
    int curr_id;
    if (get_top(stack, &curr_id) != 0) {
        return -1;
    }

    // 检查是否重名
    int dummy_id, dummy_is_dir;
    if (get_id_and_isdir_by_name(conn, name, curr_id, user_name, &dummy_id, &dummy_is_dir) == 0) {
        // 已存在
        return -1;
    }

    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) {
        fprintf(stderr, "mysql_stmt_init failed\n");
        return -1;
    }

    const char* query = "INSERT INTO nodes (name, is_dir, p_id, user_name) VALUES (?, 1, ?, ?)";
    if (mysql_stmt_prepare(stmt, query, strlen(query)) != 0) {
        fprintf(stderr, "mysql_stmt_prepare failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    MYSQL_BIND bind[3];
    memset(bind, 0, sizeof(bind));

    // name
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (void*)name;
    bind[0].buffer_length = strlen(name);

    // p_id
    bind[1].buffer_type = MYSQL_TYPE_LONG;
    bind[1].buffer = (void*)&curr_id;

    // user_name
    bind[2].buffer_type = MYSQL_TYPE_STRING;
    bind[2].buffer = (void*)user_name;
    bind[2].buffer_length = strlen(user_name);

    if (mysql_stmt_bind_param(stmt, bind) != 0) {
        fprintf(stderr, "mysql_stmt_bind_param failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    if (mysql_stmt_execute(stmt) != 0) {
        fprintf(stderr, "mysql_stmt_execute failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    mysql_stmt_close(stmt);
    return 0;
}

